﻿using Microsoft.EntityFrameworkCore;

using SRM.Application.PageResult.Dtos;
using SRM.Application.PageResult.IServices;
using SRM.Core.Models;
using SRM.Core.Models.Base;
using SRM.Core.Repositories;

using System.Linq;
using System.Threading.Tasks;

namespace SRM.Application.PageResult.PurchaseOrderPage
{
    public class PurchaseOrderServer : IPurchaseOrderServer
    {
        private readonly IRepository<PurchaseOrder> _purchaseOrderRepository;

        public PurchaseOrderServer(IRepository<PurchaseOrder> purchaseOrderRepository)
        {
            _purchaseOrderRepository = purchaseOrderRepository;
        }

        public async Task<PagerModel<PurchaseOrder>> GetPurchaseOrderList(PagerModelInput input)
        {
            var query = await _purchaseOrderRepository.GetAllListAsync();
            if (!string.IsNullOrEmpty(input.FilterText))
            {
                query = query.Where(s => s.PurchaseOrderNo.Contains(input.FilterText)).ToList();
            }
            if (!LoginUser.LoginUsers.IsHQ)
            {
                query = query.Where(q => q.SupplierId == LoginUser.LoginUsers.SupplierId).ToList();
            }

            query.Sort((PurchaseOrder r1, PurchaseOrder r2) => r2.CreateDate.CompareTo(r1.CreateDate));

            PagerModel<PurchaseOrder> pagerModel = PagedList<PurchaseOrder>.PageList(input, query);
            return pagerModel;
        }
    }
}
